#!/usr/bin/perl -w # useful for syntax highlighting
package clreqd_modules;

use strict;
use lvm;
use Data::Dumper;
use cldb;

sub ss_check_use_state {
my %ARGS=@_;
my $application=$ARGS{APPLICATION};
my $action=lc($ARGS{ACTION});
my $leave_imported=0;
	
	if(exists($ARGS{LEAVE_IMPORTED})) {
		$leave_imported=int($ARGS{LEAVE_IMPORTED});
	}
	my $CLDB=new cldb("$::ENV{TRUECL_CFG}/config.db");
	if(!defined($CLDB)) {
		return "ERROR Unable to connect to 'config' database.";
	}
	my $res=$CLDB->get_rows("SELECT * FROM applications WHERE name = '$application';");
	if(!defined($res->[0]->{nodes})) {
		return "ERROR Application '$application' is unknown.";
	}

	$CLDB->disconnect; $CLDB=undef;
	my $s=$res->[0]->{storage};
	#################################################################
	# Now open open the configuration database to get the storage	#
	# spec and list of volume groups...				#
	#################################################################

	if(! -f "$::ENV{TRUECL_CODE}/lib/storage_spec/$s.pm") {
		return "ERROR - Storage spec '$s' not available.";
	}

	eval "use storage_spec::$s;";
	my $STORAGE=eval "new storage_spec::$s;";
	if(!defined($STORAGE)) {
		return "ERROR Unable to use storage spec - storage_spec::$s\nError: " . eval "storage_spec::${s}::get_error_msg;";
	}
	#################################################################
	# We need to run against each vg separately.			#
	#################################################################
	my $VGS=$res->[0]->{vgs};
	my $NODES=$res->[0]->{nodes};
	my @VGLIST=split(/,/,$VGS);
	my $VG;
	my @oks=();
	my @errs=();
	my @info2;
	for $VG (@VGLIST) {
		my ($rc,@info2)=$STORAGE->check_use_state($VG,$application,$action,$NODES,$leave_imported);
		if($rc) {
			push @errs,$_ foreach(@info2);
		} else {
			push @oks,$_ foreach(@info2);
		}
	}
	# If we get any errors we return a failure, otherwise return the info
	if(@errs) {
		return "ERROR\n" . join("\n",@errs);
	}
	if(@oks) {
		return "OK\n" . join("\n",@oks);
	}
	return "OK";
}

1;
